package com.fc.happyteam.utils.tree;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.*;

@JsonSerialize
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class Node {
    @JsonIgnore
    public Integer id;

    public String value;
    public String label;

    @JsonIgnore
    public Integer parentId;
    /**
     * 孩子节点列表
     */
    public List<Node> children = null;

    // 先序遍历，拼接JSON字符串
//    public String toString() {
//        String result = "{"
//                + "name : '" + name + "'"
//                + ", label : '" + label + "'";
//
//        if (children != null && children.getSize() != 0) {
//            result += ", children : " + children.toString();
//        } else {
//            result += "";
//        }
//
//        return result + "}";
//    }

//    // 兄弟节点横向排序
//    public void sortChildren() {
//        if (children != null && children.getSize() != 0) {
//            children.sortChildren();
//        }
//    }

    // 添加孩子节点
    public void addChild(Node node) {
        if(this.children == null){
            this.children = new ArrayList<Node>();
        }
        this.children.add(node);
    }

    // 孩子节点排序
    public void sortChildren() {
        if(this.children == null){
            return;
        }
        Collections.sort(children, new NodeIDComparator());
        for (Iterator it = children.iterator(); it.hasNext(); ) {
            ((Node) it.next()).sortChildren();
        }
    }

    /**
     * 节点比较器
     */
    class NodeIDComparator implements Comparator {
        // 按照节点编号比较
        public int compare(Object o1, Object o2) {
            int j1 = ((Node) o1).id;
            int j2 = ((Node) o2).id;
            return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));
        }
    }
}
